<template>
  <el-card>
    <div class="head">
      <el-button color="#1baeae" style="color: #fff" :icon="Plus" @click="add"
        >添加</el-button
      >
      <el-button
        color="#f56c6c"
        style="color: #fff"
        :icon="Delete"
        @click="dels"
        >批量删除</el-button
      >
    </div>
    <el-table
      @selection-change="changeStatus"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="carouselUrl" label="轮播图">
        <template #default="scope">
          <img
            style="width: 150px; height: 150px"
            :src="scope.row.carouselUrl"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column prop="redirectUrl" label="跳转链接">
        <template #default="scope">
          <a href="/introduce" style="text-decoration: none; color: #6bc7ff">{{
            scope.row.redirectUrl
          }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="carouselRank" label="排序值" />
      <el-table-column prop="createTime" label="添加时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button text type="primary" @click="edit(scope.row)"
            >修改</el-button
          >
          <el-popconfirm
            @confirm="del([scope.row.carouselId])"
            title="你确定要删除吗?"
          >
            <template #reference>
              <el-button text type="primary">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        v-model:current-page="swiperData.pageNumber"
        v-model:page-size="swiperData.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="background"
        layout="prev, pager, next"
        :total="total"
        @size-change="getList"
        @current-change="getList"
      />
    </div>
  </el-card>
  <!-- 弹窗 -->
  <el-dialog v-model="dialogFormVisible" :title="title" width="500">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="图片" prop="carouselUrl">
        <el-upload
          class="avatar-uploader"
          action="http://backend-api-02.newbee.ltd/manage-api/v1/upload/file"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon :size="40" v-else class="avatar-uploader-icon"
            ><Plus
          /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="跳转链接">
        <el-input v-model="ruleForm.redirectUrl" />
      </el-form-item>
      <el-form-item label="排序值" prop="carouselRank">
        <el-input type="number" v-model="ruleForm.carouselRank" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { swiperRes } from "../../../types/type";
import { api } from "../../../api/api";
import { Plus, Delete } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import "element-plus/es/components/message/style/css";
import { useStore } from "../../../store/counter";
import type { UploadProps } from "element-plus";
const imageUrl = ref("");
const route = useRoute();
const router = useRouter();
const tableData = ref<swiperRes[]>([]);
const dialogFormVisible = ref(false);
const total = ref<number>(0);
const background = ref<boolean>(true);
const title = ref<string>("");
const store = useStore();
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
// 请求接口数据类型约束
interface swiperT {
  pageSize: number;
  pageNumber: number;
}
const swiperData = reactive<swiperT>({
  pageSize: 10,
  pageNumber: 1,
});
// 请求数据
async function getList() {
  const res: any = await api.carouselsApi(swiperData);
  tableData.value = res.data.list;
  total.value = res.data.totalCount;
}
onMounted(() => {
  getList();
});

// 表单
interface RuleForm {
  carouselUrl: string;
  redirectUrl: string;
  carouselRank: string;
  carouselId: number;
}

const ruleForm = reactive<RuleForm>({
  carouselUrl: "Hello",
  redirectUrl: "",
  carouselRank: "",
  carouselId: 0,
});

const rules = reactive<FormRules<RuleForm>>({
  carouselUrl: [{ required: true, message: "请选择照片", trigger: "blur" }],
  carouselRank: [{ required: true, message: "请选择照片", trigger: "blur" }],
});

// 清空表单
function resetForm() {
  ruleForm.carouselUrl = "";
  ruleForm.carouselRank = "";
  ruleForm.redirectUrl = "";
  ruleForm.carouselId = 0;
  imageUrl.value = "";
}
// 添加弹窗
function add() {
  dialogFormVisible.value = true;
  resetForm();
  title.value = "添加轮播图";
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (title.value == "添加轮播图") {
        api.addCarouselsApi(ruleForm).then((res: any) => {
          if (res.resultCode == 200) {
            ElMessage.success("添加成功");
            dialogFormVisible.value = false;
            getList();
          }
        });
      } else {
        api.editCarouselsApi({ ...ruleForm }).then((res: any) => {
          if (res.resultCode == 200) {
            ElMessage.success("编辑成功");
            dialogFormVisible.value = false;
            getList();
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 删除
async function del(ids: any[]) {
  const res: any = await api.deleteCarouselsApi({ ids: ids });
  if (res.resultCode == 200) {
    ElMessage.success("删除成功");
    getList();
  } else {
    ElMessage.error(res.message);
  }
}
// 批量删除勾选框
const deleteParams = ref<any[]>([]);
function changeStatus(e: any) {
  let arr: any[] = [];
  e.forEach((element: any) => {
    arr.push(element.carouselId);
  });
  deleteParams.value = arr;
}
// 批量删除
function dels() {
  del(deleteParams.value);
}
// 编辑轮播图
function edit(row: any) {
  dialogFormVisible.value = true;
  title.value = "编辑轮播图";
  ruleForm.carouselRank = row.carouselRank;
  ruleForm.redirectUrl = row.redirectUrl;
  ruleForm.carouselId = row.carouselId;
  ruleForm.carouselUrl = row.carouselUrl;
  imageUrl.value = row.carouselUrl;
}
// 图片上传成功的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = async (
  response,
  uploadFile
) => {
  const fd = new FormData();
  fd.append("file", uploadFile.raw as File);
  const res: any = await api.uploadApi(fd);
  imageUrl.value = res.data;
  ruleForm.carouselUrl = res.data;
};
// 上传文件前的钩子 可以用来约束上传图片的类型或者大小
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== 'image/png') {
    ElMessage.error('上传图片必须是png格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
};
</script>

<style lang="scss" scoped>
.head {
  height: 60px;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  width: 100%;
}
.pagination {
  width: 100%;
  display: flex;
  margin: 20px 0;
  justify-content: center;
  align-items: center;
}
.avatar-uploader {
  width: 100px;

  height: 100px;
  border: 1px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
  img {
    width: 100px;
    height: 100px;
  }
}
</style>
